package com.zide.auth.service.impl;

import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.zide.auth.constant.UserConstants;
import com.zide.auth.domain.entity.platform.*;
import com.zide.auth.domain.entity.platform.dept.PlatformDept;
import com.zide.auth.domain.vo.platform.PlatformUserRoleRespVO;
import com.zide.auth.domain.vo.request.LoginReqVO;
import com.zide.auth.domain.vo.response.MetaVo;
import com.zide.auth.domain.vo.response.RouterVo;
import com.zide.auth.domain.vo.response.UserPermiRespVO;
import com.zide.auth.mapper.platform.*;
import com.zide.auth.service.PlatformUserService;
import com.zide.auth.utils.ZiDeContext;
import com.zide.auth.utils.satoken.StpPlatformUtil;
import com.zide.auth.vo.result.PlatformUserResultVO;
import com.zide.auth.vo.search.PlatformUserSearchVO;
import com.zide.common.constant.Constants;
import com.zide.common.core.domain.PageResult;
import com.zide.common.enums.UserStatusEnum;
import com.zide.common.exception.ServiceException;
import com.zide.common.utils.StringUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.beans.Transient;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 石添添
 * @description 平台用户认证服务
 * @date 2024-09-09 22:19
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class PlatformUserServiceImpl implements PlatformUserService {

    private final PlatformUserMapper platformUserMapper;
    private final PlatformRoleMenuMapper platformRoleMenuMapper;
    private final PlatformUserRoleMapper platformUserRoleMapper;
    private final PlatformMenuMapper platformMenuMapper;
    private final PlatformRoleMapper platformRoleMapper;
    private final PlatformConfigMapper platformConfigMapper;

    @Override
    public String login(LoginReqVO reqVO) {
        String account = reqVO.getAccount();
        LambdaQueryWrapper<PlatformUser> wrapper = new LambdaQueryWrapper<PlatformUser>().eq(PlatformUser::getMobile, account);
        PlatformUser dbBean = platformUserMapper.selectOne(wrapper);
        log.info("loadUserByUsername=====>{}", dbBean);
        if (ObjectUtil.isNull(dbBean)) {
            throw new ServiceException("用户名或密码错误");
        } else if (UserStatusEnum.DISABLE.getCode().equals(dbBean.getStatus())) {
            log.info("登录用户：{} 已被停用.", account);
            throw new ServiceException("用户被锁定");
        }
        // 判断验证码
        if (!StrUtil.equals(reqVO.getCode(), "888888")) {
            throw new ServiceException("验证码错误");
        }
        StpPlatformUtil.login(dbBean.getId());
        SaTokenInfo tokenInfo = StpPlatformUtil.getTokenInfo();
        return tokenInfo.getTokenValue();
    }

    /**
     * 查询权限，从platform_tenant_user表查询权限关系
     * 1、获取当前用户id
     * 2、查询当前用户角色
     * 3、获取角色和权限关系，返回所有角色合集的菜单目录
     * 4、如果是机构所有者或者管理员，则显示所有菜单权限
     * 5、返回用户所有的店铺列表，
     * platform_tenant_user--》platform_user_role--》platform_role--》platform_role_menu--》sys_menu
     *
     * @return
     */
    @Override
    public UserPermiRespVO searchPermission() {
        Long platformUserId = ZiDeContext.getPlatformUserId();
        List<PlatformMenu> menuList;
        Set<String> permissions;
        Set<String> roles;
        if(PlatformUser.isAdmin(platformUserId)) {
            menuList = platformMenuMapper.selectList(null);
            List<PlatformRole> platformRoles = platformRoleMapper.selectList();
            roles = platformRoles.stream().map(PlatformRole::getRoleCode).collect(Collectors.toSet());
            permissions = menuList.stream().map(PlatformMenu::getMenuCode).collect(Collectors.toSet());
        }else {
            // 查询用户角色
            List<PlatformUserRoleRespVO> platformUserRoleList = platformUserRoleMapper.selectRoleList(platformUserId);
            // 获取角色编号
            Set<Long> roleIds = platformUserRoleList.stream().map(PlatformUserRoleRespVO::getRoleId).collect(Collectors.toSet());
            // 查询菜单信息
            menuList = platformRoleMenuMapper.selectMenuList(roleIds);
            roles = platformUserRoleList.stream().map(PlatformUserRoleRespVO::getRoleCode).collect(Collectors.toSet());
            permissions = menuList.stream().map(PlatformMenu::getMenuCode).collect(Collectors.toSet());
        }

        // 封装角色和菜单信息
        UserPermiRespVO result = new UserPermiRespVO();
        result.setId(platformUserId);
        result.setPermissions(permissions);
        result.setRoles(roles);
        return result;
    }

    @Override
    public void logout() {
        Long userId = ZiDeContext.getPlatformUserId();
        if (ObjectUtil.isNull(userId)) {
            throw new ServiceException("无效登录信息");
        }
        StpPlatformUtil.logout(userId);
    }

    /**
     * 构建导航菜单
     * @return
     */
    public List<RouterVo> buildMenus() {
        Long userId = ZiDeContext.getPlatformUserId();
        List<PlatformMenu> platformMenus;
        if(PlatformUser.isAdmin(userId)) {
            platformMenus = platformMenuMapper.selectMenuTreeAll();
        }else {
            platformMenus = platformRoleMenuMapper.selectPlatformMenuList(userId);
        }
        List<PlatformMenu> childPerms = getChildPerms(platformMenus, 0L);
        // 设置路由信息
        return buildMenus(childPerms);
    }

    @Override
    public PageResult<PlatformUserResultVO> selectAllocatedList(PlatformUserSearchVO searchVO) {
        MPJLambdaWrapper<PlatformUser> wrapper = new MPJLambdaWrapper<>();

        wrapper.select(PlatformUser::getId,PlatformUser::getDeptId,PlatformUser::getUsername,PlatformUser::getNickname,
                        PlatformUser::getMobile,PlatformUser::getStatus,PlatformUser::getCreateTime)
                .leftJoin(PlatformDept.class,PlatformDept::getId,PlatformUser::getDeptId)
                .leftJoin(PlatformUserRole.class,PlatformUserRole::getUserId,PlatformUser::getId)
                .leftJoin(PlatformRole.class,PlatformRole::getId,PlatformUserRole::getRoleId)
                .eq(PlatformRole::getId,searchVO.getRoleId());
        if(StrUtil.isNotEmpty(searchVO.getUsername())) {
            wrapper.like(PlatformUser::getUsername,searchVO.getUsername());
        }
        if(StrUtil.isNotEmpty(searchVO.getMobile())) {
            wrapper.like(PlatformUser::getMobile,searchVO.getMobile());
        }
        return platformUserMapper.selectJoinPage(searchVO,PlatformUserResultVO.class, wrapper);
    }

    @Override
    public PageResult<PlatformUserResultVO> selectUnallocatedList(PlatformUserSearchVO searchVO) {
        Page<PlatformUser> page = new Page<>();
        page.setSize(searchVO.getPageSize());
        page.setCurrent(searchVO.getPageNum());
        Page<PlatformUser> sysUsers = platformUserMapper.selectUnallocatedList(page,searchVO);
        PageResult<PlatformUserResultVO> resultVO = new PageResult<>();
        List<PlatformUser> records = sysUsers.getRecords();

        resultVO.setList(BeanUtil.copyToList(records,PlatformUserResultVO.class));
        resultVO.setTotal(sysUsers.getTotal());
        return resultVO;
    }

    @Override
    public PageResult<PlatformUserResultVO> selectPage(PlatformUserSearchVO searchVO) {

        return platformUserMapper.selectPage(searchVO);
    }

    /**
     * 无分页查询
     */
    @Override
    public List<PlatformUserResultVO> selectUserList(PlatformUser user) {

        MPJLambdaWrapper<PlatformUser> wrapper = new MPJLambdaWrapper<>();
        wrapper.selectAll(PlatformUser.class)
                .leftJoin(PlatformDept.class,PlatformDept::getId,PlatformUser::getDeptId)
                .selectAs(PlatformDept::getDeptName,PlatformUserResultVO::getDeptName)
                .selectAs(PlatformDept::getId,PlatformUserResultVO::getDeptId);
        if(StrUtil.isNotEmpty(user.getUsername())) {
            wrapper.like(PlatformUser::getUsername,user.getUsername());
        }
        if(StrUtil.isNotEmpty(user.getMobile())) {
            wrapper.like(PlatformUser::getMobile,user.getMobile());
        }

        return platformUserMapper.selectJoinList(PlatformUserResultVO.class, wrapper);
    }

    /**
     * 导入用户
     * @param userList
     * @param updateSupport
     * @param userId
     * @return
     */
    @Override
    public String importUser(List<PlatformUser> userList, boolean updateSupport, Long userId) {
        if (StringUtils.isNull(userList) || userList.size() == 0) {
            throw new ServiceException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        PlatformConfig platformConfig = platformConfigMapper.selectOne(new LambdaQueryWrapper<PlatformConfig>().eq(PlatformConfig::getConfigCode, "platform.user.initPassword"));
        String defaultPassword = "123456";
        if(ObjectUtil.isNotNull(platformConfig)) {
            defaultPassword = platformConfig.getConfigValue();
        }
        String password = SaSecureUtil.sha256(defaultPassword);


        for (PlatformUser user : userList) {
            try {
                // 验证是否存在这个用户
                PlatformUser u = platformUserMapper.selectOne(new LambdaQueryWrapper<PlatformUser>().eq(PlatformUser::getMobile,user.getMobile()));
                if (StringUtils.isNull(u)) {
                    user.setPassword(password);
                    platformUserMapper.insert(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getMobile() + " 导入成功");
                } else if (updateSupport) {

                    user.setId(u.getId());
                    platformUserMapper.updateById(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getMobile() + " 更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、账号 " + user.getMobile() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + user.getMobile() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();

    }

    @Override
    public PlatformUser selectUserById(Long userId) {
        return platformUserMapper.selectById(userId);
    }

    private boolean checkPhoneUnique(PlatformUser user) {
        PlatformUser platformUser = platformUserMapper.selectOne(new LambdaQueryWrapper<PlatformUser>().eq(PlatformUser::getMobile, user.getMobile()));
        Long userId = user.getId();
        if(ObjectUtil.isNull(platformUser) || ObjectUtil.isNull(userId)) {
            return false;
        }
        return Objects.equals(platformUser.getId(), userId);
    }

    @Override
    public int insertUser(PlatformUser user) {
        if (StringUtils.isNotEmpty(user.getMobile()) && checkPhoneUnique(user)) {
            throw new ServiceException("新增用户'" + user.getMobile() + "'失败，手机号码已存在");
        }
        user.setPassword(SaSecureUtil.sha256(platformConfigMapper.selectOne(new LambdaQueryWrapper<PlatformConfig>().eq(PlatformConfig::getConfigCode, "platform.user.initPassword")).getConfigValue()));
        return platformUserMapper.insert(user);
    }

    @Override
    public int updateUser(PlatformUser user) {
        if (StringUtils.isNotEmpty(user.getMobile()) && checkPhoneUnique(user)) {
            throw new ServiceException("新增用户'" + user.getMobile() + "'失败，手机号码已存在");
        }
        return platformUserMapper.updateById(user);
    }

    @Override
    public int resetPwd(PlatformUser user) {
        user.setPassword(SaSecureUtil.sha256(platformConfigMapper.selectOne(new LambdaQueryWrapper<PlatformConfig>().eq(PlatformConfig::getConfigCode, "platform.user.initPassword")).getConfigValue()));
        return platformUserMapper.updateById(user);
    }

    @Override
    public int updateUserStatus(PlatformUser user) {

        return platformUserMapper.updateById(user);
    }

    @Override
    public boolean insertUserAuth(Long userId, Long[] roleIds) {
        platformUserRoleMapper.delete(new LambdaQueryWrapper<PlatformUserRole>().eq(PlatformUserRole::getUserId, userId));
        List<PlatformUserRole> insertBean = new ArrayList<>();
        for (Long roleId : roleIds) {
            insertBean.add(new PlatformUserRole(userId,roleId));
        }
        return platformUserRoleMapper.insertBatch(insertBean);
    }

    /**
     * 删除用户
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int deleteUserByIds(Long[] userIds) {
        platformUserMapper.deleteBatchIds(Arrays.asList(userIds));

        return platformUserRoleMapper.delete(new LambdaQueryWrapper<PlatformUserRole>().in(PlatformUserRole::getUserId, Arrays.asList(userIds)));
    }

    public List<RouterVo> buildMenus(List<PlatformMenu> menus) {
        List<RouterVo> routers = new LinkedList<>();
        for (PlatformMenu menu : menus) {
            RouterVo router = new RouterVo();
            router.setHidden(1 == menu.getShow());
            router.setName(getRouteName(menu));
            router.setPath(getRouterPath(menu));
            router.setComponent(getComponent(menu));
            router.setQuery(menu.getQuery());
            router.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(),false, menu.getMenuRouter()));
            List<PlatformMenu> cMenus = menu.getChildren();
            if (ObjectUtil.isNotEmpty(cMenus) && UserConstants.TYPE_DIR.equals(menu.getMenuType())) {
                router.setAlwaysShow(true);
                router.setRedirect("noRedirect");
                router.setChildren(buildMenus(cMenus));
            } else if (isMenuFrame(menu)) {
                router.setMeta(null);
                List<RouterVo> childrenList = new ArrayList<>();
                RouterVo children = new RouterVo();
                children.setPath(menu.getMenuRouter());
                children.setComponent(menu.getComponent());
                children.setName(StringUtils.capitalize(menu.getMenuRouter()));
                children.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), false,menu.getMenuRouter()));
                children.setQuery(menu.getQuery());
                childrenList.add(children);
                router.setChildren(childrenList);
            } else if (menu.getParentId().intValue() == 0 && isInnerLink(menu)) {
                router.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon()));
                router.setPath("/");
                List<RouterVo> childrenList = new ArrayList<>();
                RouterVo children = new RouterVo();
                String routerPath = innerLinkReplaceEach(menu.getMenuRouter());
                children.setPath(routerPath);
                children.setComponent(UserConstants.INNER_LINK);
                children.setName(StringUtils.capitalize(routerPath));
                children.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), menu.getMenuRouter()));
                childrenList.add(children);
                router.setChildren(childrenList);
            }
            routers.add(router);
        }
        return routers;
    }

    /**
     * 根据父节点的ID获取所有子节点
     *
     * @param list     分类表
     * @param parentId 传入的父节点ID
     * @return String
     */
    private List<PlatformMenu> getChildPerms(List<PlatformMenu> list, Long parentId) {
        List<PlatformMenu> returnList = new ArrayList<>();
        for (PlatformMenu t : list) {
            // 一、根据传入的某个父节点ID,遍历该父节点的所有子节点
            if (t.getParentId().equals(parentId)) {
                recursionFn(list, t);
                returnList.add(t);
            }
        }
        return returnList;
    }
    /**
     * 递归列表
     *
     * @param list 分类表
     * @param t    子节点
     */
    private void recursionFn(List<PlatformMenu> list, PlatformMenu t) {
        // 得到子节点列表
        List<PlatformMenu> childList = getChildList(list, t);
        t.setChildren(childList);
        for (PlatformMenu tChild : childList) {
            if (hasChild(list, tChild)) {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<PlatformMenu> getChildList(List<PlatformMenu> list, PlatformMenu t) {
        List<PlatformMenu> tlist = new ArrayList<>();
        for (PlatformMenu n : list) {
            if (n.getParentId().longValue() == t.getId().longValue()) {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 获取路由名称
     *
     * @param menu 菜单信息
     * @return 路由名称
     */
    public String getRouteName(PlatformMenu menu) {
        String routerName = StringUtils.capitalize(menu.getMenuRouter());
        // 非外链并且是一级目录（类型为目录）
        if (isMenuFrame(menu)) {
            routerName = StringUtils.EMPTY;
        }
        return routerName;
    }

    /**
     * 获取路由地址
     *
     * @param menu 菜单信息
     * @return 路由地址
     */
    public String getRouterPath(PlatformMenu menu) {
        String routerPath = menu.getMenuRouter();
        // 内链打开外网方式
        if (menu.getParentId().intValue() != 0 && isInnerLink(menu)) {
            routerPath = innerLinkReplaceEach(routerPath);
        }
        // 非外链并且是一级目录（类型为目录）
        if (0 == menu.getParentId().intValue() && UserConstants.TYPE_DIR.equals(menu.getMenuType())
                && UserConstants.NO_FRAME.equals(menu.getIsFrame())) {
            routerPath = "/" + menu.getMenuRouter();
        }
        // 非外链并且是一级目录（类型为菜单）
        else if (isMenuFrame(menu)) {
            routerPath = "/";
        }
        return routerPath;
    }

    /**
     * 获取组件信息
     *
     * @param menu 菜单信息
     * @return 组件信息
     */
    public String getComponent(PlatformMenu menu) {
        String component = UserConstants.LAYOUT;
        if (StrUtil.isNotEmpty(menu.getComponent()) && !isMenuFrame(menu)) {
            component = menu.getComponent();
        } else if (StrUtil.isEmpty(menu.getComponent()) && menu.getParentId().intValue() != 0 && isInnerLink(menu)) {
            component = UserConstants.INNER_LINK;
        } else if (StrUtil.isEmpty(menu.getComponent()) && isParentView(menu)) {
            component = UserConstants.PARENT_VIEW;
        }
        return component;
    }

    /**
     * 是否为parent_view组件
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isParentView(PlatformMenu menu) {
        return menu.getParentId().intValue() != 0 && UserConstants.TYPE_DIR.equals(menu.getMenuType());
    }

    /**
     * 是否为菜单内部跳转
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isMenuFrame(PlatformMenu menu) {
        return menu.getParentId().intValue() == 0 && UserConstants.TYPE_MENU.equals(menu.getMenuType())
                && menu.getIsFrame().equals(UserConstants.NO_FRAME);
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<PlatformMenu> list, PlatformMenu t) {
        return getChildList(list, t).size() > 0;
    }

    /**
     * 内链域名特殊字符替换
     *
     * @return 替换后的内链域名
     */
    public String innerLinkReplaceEach(String path) {
        return StringUtils.replaceEach(path, new String[]{Constants.HTTP, Constants.HTTPS, Constants.WWW, ".", ":"},
                new String[]{"", "", "", "/", "/"});
    }
    /**
     * 是否为内链组件
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isInnerLink(PlatformMenu menu) {
        return menu.getIsFrame().equals(UserConstants.NO_FRAME) && StringUtils.ishttp(menu.getMenuRouter());
    }
}
